package algorithm;

/**
 * 对多个有序数组进行排序（数组之间是无序的），使用场景：比如分库分表中的按序查询的结果集合并
 */
public class ThirdArraySort {

    public static void main(String[] args) {
        int[][] arrs = new int[][]{
                {1, 5, 9, 10},
                {2, 4, 11},
                {3, 6, 7}
        };

        int[] cursors = new int[arrs.length];

        int size = 0;
        for (int[] arr : arrs) {
            size += arr.length;
        }

        for (int i = 0; i < size; i++) {
            int min = min(arrs, cursors);
            System.out.println(min);
        }
    }

    public static int min(int[][] arrs, int[] cursors) {
        int minIndex = 0, min = Integer.MAX_VALUE;
        for (int i = 0; i < arrs.length; i++) {
            if (cursors[i] >= arrs[i].length) {
                continue;
            }
            if (arrs[i][cursors[i]] < min) {
                minIndex = i;
                min = arrs[i][cursors[i]];
            }
        }
        cursors[minIndex]++;
        return min;
    }
}
